import 'dart:async';

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'dart:convert';

import '/api/Api.dart';
import '/model/User.dart';
import 'ShowPostCasePage.dart';

// FB 意思是 FutureBuilder

class PostCaseFBPage extends StatefulWidget {
  Map? arguments;
  PostCaseFBPage({this.arguments});

  @override
  _PostCaseFBPageState createState() =>
      _PostCaseFBPageState(arguments: this.arguments);
}

class _PostCaseFBPageState extends State<PostCaseFBPage> {
  var _futureBuilderFuture;
  Map? arguments;

  String title = '诊断结果';
  Map? caseResult;

  _PostCaseFBPageState({this.arguments});

  @override
  void initState() {
    super.initState();

    ///用_futureBuilderFuture来保存_gerData()的结果，以避免不必要的ui重绘
    _futureBuilderFuture = _posCase();
  }

  @override
  Widget build(BuildContext context) {
    print('进了FB');
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            title = title + '.';
          });
        },
        child: Icon(Icons.title),
      ),
      body: RefreshIndicator(
        onRefresh: _posCase,
        child: FutureBuilder(
          builder: _buildFuture,
          future:
              _futureBuilderFuture, // 用户定义的需要异步执行的代码，类型为Future<String>或者null的变量或函数
        ),
      ),
    );
  }

  Widget _buildFuture(BuildContext context, AsyncSnapshot snapshot) {
    print('进了_buildFuture');
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        print('还没有开始网络请求');
        return Text('还没有开始网络请求');
      case ConnectionState.active:
        print('active');
        return Text('ConnectionState.active');
      case ConnectionState.waiting:
        print('waiting');
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.done:
        print('done');
        if (snapshot.hasError) return Text('Error: ${snapshot.error}');
        // return _createListView(context, snapshot);
        return ShowPostCasePage(arguments: caseResult);
      default:
        return Text('还没有开始网络请求');
    }
  }

  Future _posCase() async {
    String url = API.BASE_URL + API.POST_CASE;
    print('请求的url：$url');
    Response response;

    try {
      var dio = Dio();

      List photosList = [];

      // mFlieList.forEach((element) {
      //   photosList.add(
      //       MultipartFile.fromFileSync(element.path, filename: 'upload.txt'));
      // });

      for (var i = 0; i < arguments!['photos'].length; i++) {
        var fn = i.toString() + '.png';
        photosList.add(MultipartFile.fromFileSync(arguments!['photos'][i].path,
            filename: fn));
      }

      var formData = FormData.fromMap({
        'patient_name': arguments!['name'],
        'patient_idcard_num': arguments!['idNum'],
        'phone_num': arguments!['phoneNum'],
        'patient_age': arguments!['age'],
        'uploder': User.job_num,
        'allergy_history': arguments!['history'],
        'habits': arguments!['habits'],
        'photos': photosList
      });

      response = await dio.post(url, data: formData);

      // Map<String, dynamic> caseInfo = json.decode(response.data);
      Map<String, dynamic> caseInfo = Map<String, dynamic>.from(response.data);
      print(caseInfo.toString());

      caseResult = caseInfo;

      return caseInfo;
    } catch (e) {
      print(e);
    }
  }
}
